<?php
namespace app\controllers;
use Yii;
use yii\helpers\Url;
use yii\db\Query;
use yii\helpers\VarDumper;

class QueueController extends BaseController
{
    /**
     * 队列管理列表
     * @return string|\yii\web\Response
     */
    public function actionIndex()
    {
        if (Yii::$app->request->isAjax){
            $db = (new Query())->from('queues_config');
            $count = $db->count('extension',$this->asterisk_db);
            $page = Yii::$app->request->get('page',1);
            $limit = Yii::$app->request->get('limit',10);
            $data = $db->offset(($page-1)*$limit)->limit($limit)->all($this->asterisk_db);
            foreach ($data as &$d){
                $d['edit_url'] = Url::to(['edit','extension'=>$d['extension']]);
                $d['destroy_url'] = Url::to(['destroy','extension'=>$d['extension']]);
                $config = (new Query())->from('queues_details')->where(['id'=>$d['extension']])->select(['keyword','data'])->indexBy('keyword')->all($this->asterisk_db);
                $d['strategy'] = Yii::$app->params['ring_strategy'][$config['strategy']['data']];
                $d['cwignore_text'] = Yii::$app->params['cwignore'][$d['cwignore']];
                $d['monitor_type_text'] = $d['monitor_type']=='b'?'接通后录音':'包括振铃';
                $d['monitor-format'] = $config['monitor-format']['data']?$config['monitor-format']['data']:'-';
            }
            return $this->asJson([
                'code' => 0,
                'msg' => '请求成功',
                'count' => $count,
                'data' => $data
            ]);
        }
        return $this->render('index');
    }

    /**
     * 添加队列
     * @return string|\yii\web\Response
     */
    public function actionCreate()
    {
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $transaction = $this->asterisk_db->beginTransaction();
            try{
                //写入queues_config表
                $config = array_merge(Yii::$app->params['queues_config_template'],[
                    'extension'     => $data['extension'],
                    'descr'         => $data['descr'],
                    'cwignore'      => $data['cwignore'],
                    'monitor_type'  => $data['monitor_type'],
                ]);
                $this->asterisk_db->createCommand()->insert('queues_config',$config)->execute();
                //写入queues_details表
                $details = array_merge(Yii::$app->params['queues_details_template'],[
                    'strategy'=>$data['strategy'],
                    'monitor-format'=>$data['monitor-format'],
                ]);
                $details_column = ['id','keyword','data','flags'];
                $details_data = [];
                foreach($details as $k=>$v){
                    array_push($details_data,[$data['extension'],$k,$v,0]);
                }
                if (trim($data['members'])){
                    $members_cont = explode("\n",trim($data['members']));
                    foreach ($members_cont as $k=>$m){
                        $item = explode(",",trim($m));
                        array_push($details_data,[$data['extension'],'member','Local/'.$item[0].'@from-queue/n,0',$k]);
                    }
                }
                $this->asterisk_db->createCommand()->batchInsert('queues_details',$details_column,$details_data)->execute();
                //写入asterisk database
                $this->ami->DatabasePut('QPENALTY/'.$data['extension'],'dynmemberonly','no');
                $transaction->commit();
                $this->reload();
                return $this->asJson(['code'=>0,'msg'=>'添加成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'添加失败','data'=>$exception->getMessage()]);
            }
        }
        $members = (new Query())->from('users')->select(['extension','name'])->all($this->asterisk_db);
        return $this->render('create',['members'=>$members]);
    }

    /**
     * 编辑队列
     * @return string
     */
    public function actionEdit()
    {
        $extension = Yii::$app->request->get('extension');
        if (Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            $transaction = $this->asterisk_db->beginTransaction();
            try{
                //更新queues_config表
                $config = array_merge(Yii::$app->params['queues_config_template'],[
                    'descr'         => $data['descr'],
                    'cwignore'      => $data['cwignore'],
                    'monitor_type'  => $data['monitor_type'],
                ]);
                $this->asterisk_db->createCommand()->update('queues_config',$config,['extension' => $extension])->execute();
                //更新queues_details表
                $this->asterisk_db->createCommand()->delete('queues_details',['id' => $extension])->execute();
                $details = array_merge(Yii::$app->params['queues_details_template'],[
                    'strategy'=>$data['strategy'],
                    'monitor-format'=>$data['monitor-format'],
                ]);
                $details_column = ['id','keyword','data','flags'];
                $details_data = [];
                foreach($details as $k=>$v){
                    array_push($details_data,[$extension,$k,$v,0]);
                }
                if (trim($data['members'])){
                    $members_cont = explode("\n",trim($data['members']));
                    foreach ($members_cont as $k=>$m){
                        $item = explode(",",trim($m));
                        array_push($details_data,[$extension,'member','Local/'.$item[0].'@from-queue/n,0',$k]);
                    }
                }
                $this->asterisk_db->createCommand()->batchInsert('queues_details',$details_column,$details_data)->execute();
                //写入asterisk database
                $this->ami->DatabasePut('QPENALTY/'.$extension,'dynmemberonly','no');
                $transaction->commit();
                $this->reload();
                return $this->asJson(['code'=>0,'msg'=>'更新成功']);
            }catch (\Exception $exception){
                $transaction->rollBack();
                return $this->asJson(['code'=>1,'msg'=>'更新失败','data'=>$exception->getMessage()]);
            }
        }
        $config = (new Query())->from('queues_config')->where(['extension'=>$extension])->one($this->asterisk_db);
        $details_data = (new Query())->from('queues_details')->where(['id'=>$extension])->all($this->asterisk_db);
        $member_str = '';
        $details = [];
        foreach ($details_data as $m){
            if($m['keyword']=='member'){
                if (preg_match('/Local\/(\d+)\@from-queue\/n,0/',$m['data'],$arr)){
                    $member_str .= $arr[1].",0\n";
                }
            }else{
                $details[$m['keyword']] = $m['data'];
            }
        }

        $members = (new Query())->from('users')->select(['extension','name'])->all($this->asterisk_db);
        return $this->render('edit',['members'=>$members,'config'=>$config,'details'=>$details,'member_str'=>$member_str]);
    }

    /**
     * 删除队列
     * @return \yii\web\Response
     */
    public function actionDestroy()
    {
        $extension = Yii::$app->request->post('extension');
        $transaction = $this->asterisk_db->beginTransaction();
        try{
            //删除queues_config表
            $this->asterisk_db->createCommand()->delete('queues_config',['extension'=>$extension])->execute();
            //删除queues_details表
            $this->asterisk_db->createCommand()->delete('queues_details',['id'=>$extension])->execute();
            $this->ami->DatabaseDel('QPENALTY/'.$extension,'dynmemberonly');
            $transaction->commit();
            $this->reload();
            return $this->asJson(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            $transaction->rollBack();
            return $this->asJson(['code'=>1,'msg'=>'删除失败','data'=>$exception->getMessage()]);
        }
    }
    
}